import { ComUtils } from "@/utils/Com"
import { createSignal, For, onMount, Show } from "solid-js"
import '@/assets/css/win-popup.css'

export default function Popup() {
    const [projects, setProjects] = createSignal<ProjectItem[]>([]);
    const [errMsg, setErrMsg] = createSignal('');
    const [isDev, setIsDev] = createSignal(true);

    const [tab, setTab] = createSignal(0);

    const loadData = async () => {
        const dev = await ComUtils.callChromeMethod<boolean>('isDev', {})
            .catch(() => false)
        setIsDev(dev)
        const data = await ComUtils.callChromeMethod<ProjectItem[]>('loadPopupData', {});
        setProjects(data.filter(i => i.type !== 'editorPlugin'))
    }

    const runScript = async (item: ProjectItem) => {
        if (item.type === 'content') {
            return;
        }
        try {
            await ComUtils.callChromeMethod('runScript', { id: item.id, sw: screen.width, sh: screen.height })
            if (item.type === 'sidePanel') {
                await ComUtils.callChromeMethod('openSidePanel', undefined)
            }
            window.close()
        } catch (error) {
            console.log(error)
            setErrMsg(ComUtils.tr('run_fail'))
        }
    }

    const openManager = () => {
        ComUtils.callChromeMethod('openSettings', undefined)
    }

    const openExtensionPage = () => {
        if (navigator.userAgent.toLowerCase().indexOf('edge') >= 0) {
            ComUtils.callChromeMethod('openTab', { url: 'edge://extensions/' })
        } else {
            ComUtils.callChromeMethod('openTab', { url: 'chrome://extensions/' })
        }

    }

    const getData = () => {
        return projects().filter(p => {
            if (tab() === 0) {
                return p.type === 'sidePanel' || p.type === 'window'
            } else {
                return p.type === 'content'
            }
        })
    }

    const switchTabs = (index: number) => {
        setTab(index)
    }

    const dispatchMenuEvents = (id: string) => {
        ComUtils.callChromeMethod('dispatchMenuEvents', id)
    }

    onMount(() => {
        ComUtils.callChromeMethod('initPopup', undefined)
        loadData()
    })

    const DevWarn = <>
        <div class="flex justify-end items-center gap-4 mb-4">
            <a class="text-[#42A5F5] underline text-xs" href="https://jianghong2021.github.io/script-dog-doc/" target="_blank" rel="noopener noreferrer">
                {ComUtils.tr('how_to_use')}
            </a>
        </div>
        <h2 class="font-bold" classList={{ 'text-[#a72b04]': !isDev() }}>
            <button class="btn text-xs" onclick={openExtensionPage}>
                {ComUtils.tr('need_dev_mode')}
            </button>
        </h2>
        <p class="text-[#999] mt-3 text-xs">
            {ComUtils.tr('need_dev_mode_desc')}
        </p>
    </>

    const RunBtnDom = (props: { data: ProjectItem }) => <button class="flex items-center gap-2 py-1 px-2 text-gray-400 hover:bg-[#303030] hover:text-white" title={ComUtils.tr('project_type_' + (props.data.type || 'content'))} onclick={() => runScript(props.data)}>
        <span class=" text-ellipsis overflow-hidden whitespace-nowrap">
            {props.data.name}
        </span>
    </button>

    const ContentScroptDom = (props: { data: ProjectItem }) => <details class="py-1 px-2 text-gray-400 hover:bg-[#303030] hover:text-white">
        <summary class="cursor-pointer text-ellipsis overflow-hidden whitespace-nowrap select-none">
            <span>
                {props.data.name}
            </span>
        </summary>
        <div class="flex gap-2 flex-wrap text-xs p-2">
            <For each={props.data.runtime?.subscriptMap}>
                {
                    sm => <button class="px-1 py-0.5 hover:text-[#f79d3c]" title={ComUtils.tr('popup_menus')} onclick={() => dispatchMenuEvents(sm.id)}>
                        {sm.title}
                    </button>
                }
            </For>
        </div>
        <Show when={!props.data.runtime?.subscriptMap || props.data.runtime?.subscriptMap.length == 0}>
            <p class="text-[#646161] text-xs">
                {ComUtils.tr('popup_menus')} {ComUtils.tr('data_empty')}
            </p>
        </Show>
    </details>

    return <div class="page p-4 w-[20rem] overflow-hidden">
        <Show when={isDev()} fallback={DevWarn}>
            <Show when={errMsg()}>
                <h3 class=" text-center text-[#e63e32]">
                    {errMsg()}
                </h3>
            </Show>
            <div class="flex gap-2 text-base pb-2">
                <button class="tab" classList={{ 'tab-active': tab() == 0 }} onclick={() => switchTabs(0)}>
                    {ComUtils.tr('project_type_window')}
                </button>
                <button class="tab" classList={{ 'tab-active': tab() == 1 }} onclick={() => switchTabs(1)}>
                    {ComUtils.tr('project_type_content')}
                </button>
            </div>
            <div class="flex flex-col h-[18rem] overflow-y-auto text-sm">
                <For each={getData()}>
                    {
                        project => <Show when={tab() === 0} fallback={<ContentScroptDom data={project} />}>
                            <RunBtnDom data={project} />
                        </Show>
                    }
                </For>
                <Show when={getData().length === 0}>
                    <p class=" text-[#646363] text-xs text-center mt-8">
                        {ComUtils.tr('data_empty')}
                    </p>
                </Show>
            </div>
            <button class="btn mt-4 w-full" onclick={openManager}>
                {ComUtils.tr('manage_project')}
            </button>
        </Show>
    </div>
}